package com.treasure.service.helper;

import org.imgscalr.Scalr;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 图片压缩
 */
public class PictureHelper {
    static TLogger log = LoggerManager.getLogger(PictureHelper.class);

	/**
	 * 压缩图片的流文件，产生的图片为jpg格式
     * 分辨率不超过720 可以根据情况调整
	 * @param source 只支持图片文件
	 * @return
	 */
	public static ByteArrayOutputStream compressInS(InputStream source) {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
            BufferedImage originalImage;
            int width = 720;
            int height = 720;
            originalImage = ImageIO.read(source);
            if (originalImage.getWidth() > width
                || originalImage.getHeight() > height) {
                double rate1 = ((double) originalImage.getWidth())
                    / (double) width;
                double rate2 = ((double) originalImage.getHeight())
                    / (double) height;
                // 根据缩放比率大的进行缩放控制
                double rate = rate1 > rate2 ? rate1 : rate2;
                width = (int) (((double) originalImage.getWidth()) / rate);
                height = (int) (((double) originalImage.getHeight()) / rate);
            } else {
                width = originalImage.getWidth();
                height = originalImage.getHeight();
            }
            BufferedImage thumbnail = Scalr.resize(originalImage,
                Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, width,
                height, Scalr.OP_ANTIALIAS);

            os = new ByteArrayOutputStream();

            if (!ImageIO.write(thumbnail, "jpg", os)) {
                log.error("File write failed.",null);
                throw new IllegalStateException("转换流文件失败");
            }
		} catch (Exception e) {
			log.error("图片格式错误，压缩失败",e);
            throw new IllegalStateException("压缩失败",e);
		} finally {
			try {
				if (os != null)
					os.close();
			} catch (IOException e) {
			}
		}
		return os;
	}

}
